package com.gitee.hermer.engine.jars.app.sdk.configuration;

import javax.sql.DataSource;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.TransactionManagementConfigurer;
import com.gitee.hermer.boot.jee.commons.bean.utils.BeanLocator;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.engine.jars.core.autoconfigure.annotate.ConditionalOnBean;
import com.gitee.hermer.engine.jars.core.autoconfigure.annotate.ConditionalOnEngineBean;
import com.gitee.hermer.engine.jars.core.autoconfigure.annotate.ConditionalOnMissingBean;

@Configuration
@ConditionalOnBean(DataSource.class)
public class EngineAppXATransactionAutoConfiguration extends UtilsContext implements Ordered,TransactionManagementConfigurer,ApplicationContextAware{

	private ApplicationContext applicationContext;

	@Autowired(required=false)
	private DataSource dataSource;

	@Override
	public int getOrder() {
		return HIGHEST_PRECEDENCE+100;
	}

	@Bean
	@Order(0)
	//@Conditional(EngineXATransactionSpanCondition.class)
	@ConditionalOnEngineBean(PlatformTransactionManager.class)
	public PlatformTransactionManager getJtaTransactionManager(){
		try {
			info("启动JTA事物管理器...");
			return BeanLocator.getBean(PlatformTransactionManager.class);
		} catch (Exception e) {
			error(e.getMessage(),e);
			throw new IllegalStateException(e.getMessage(),e);
		}
	}

	@Bean
	@Order(1)
	@ConditionalOnMissingBean(PlatformTransactionManager.class)
	public PlatformTransactionManager dataSourceTransactionManager(){
		info("启动默认事物管理器...");
		return new DataSourceTransactionManager(dataSource);
	}

	@Override
	public PlatformTransactionManager annotationDrivenTransactionManager() {
		try{
			return applicationContext.getBean(PlatformTransactionManager.class);
		}catch (Exception e) {
			return null;
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}

}
